package com.gz.mylife.app;

import java.lang.ref.WeakReference;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.OfflineDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.account.LoginPlatform;
import com.zl.smartmall.library.account.po.UserInfo;
import com.zl.smartmall.library.listener.CheckVersionListener;
import com.zl.smartmall.library.listener.LogoutListener;
import com.zl.smartmall.library.listener.UserInfoListener;
import com.zl.smartmall.library.os.System;
import com.zl.smartmall.library.os.po.CheckVersionInfo;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.Tools;

/**
 * 
 * @author 陈希然
 * 
 */
public class FragmentPersonal extends Fragment implements OnClickListener {

	private static final String TAG = FragmentPersonal.class.getSimpleName();

	private Context mContext;

	private View mConvertView;
	private boolean isLogin;
	private ImageView mIvFace;
	private ImageView mIvVersionNew;
	private TextView mTvNickname;
	private TextView mTvID;
	private TextView mTvJifen;
	private TextView mTvLogin;
	private TextView mTvUnlogin;
	private TextView mTvVersion;
	private RelativeLayout mRlCollection;
	private RelativeLayout mRlOrderList;
	private RelativeLayout mRlCustiomservice;
	private RelativeLayout mRlVersion;
	private RelativeLayout mRlLoginOut;
	private LinearLayout mRlMyCommunity;
	private OfflineDialog mOfflineDialog;
	private Dialog mLoadingDialog;

	public static UserInfo mUserInfo;
	private MyUserInfoListener mUserInfoListener;
	private DisplayImageOptions mFaceOptions;
	private MyCheckVersionListener mCheckVersionListener;
	private LinearLayout customer_service;
	public static TextView tvpoint;//当前登录用户的id
	private LinearLayout shop_info;//加盟商
	private LinearLayout erweima;//二维码
	private LinearLayout ly_agree;//用户注册协议
	private LinearLayout ly_message;//物业推送的通知

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		CrashHandler.d(TAG, TAG + " onCreate");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, TAG + " onCreateView");
		if (mConvertView == null) {
			CrashHandler.d(TAG, "convertView is null, init the whole elements");
			mConvertView = inflater.inflate(R.layout.fragment_personal,
					container, false);

			init(inflater);
			mUserInfoListener = new MyUserInfoListener(this);
			mCheckVersionListener = new MyCheckVersionListener(this);
			mUserInfo = IAuth.getInstance().loadUserInfo();
			mLoadingDialog = new Dialog(getActivity(), R.style.DialogTheme);
			mLoadingDialog.setContentView(R.layout.loading_data_dialog2);
			initView();
			System.checkVersion(getActivity(), "smh", mCheckVersionListener);
		}
		// ((BaseActionBarActivity) getActivity()).mActionBar.setTitle("营养专栏");
		return mConvertView;
	}

	private void initView() {
		if (mUserInfo == null) {
			isLogin = false;
		} else {
			isLogin = true;
			ImageLoader.getInstance().displayImage(mUserInfo.getFace(),
					mIvFace, mFaceOptions);
			mTvNickname.setText(mUserInfo.getNickname());
			mTvID.setText("会员号：" + mUserInfo.getUid());
			mTvJifen.setText("可用" + 0 + "积分");
			
		}
		
		checkViewShow();
		checkNewVersion();

		mRlCollection.setOnClickListener(this);
		mRlOrderList.setOnClickListener(this);
		mRlCustiomservice.setOnClickListener(this);
		mRlVersion.setOnClickListener(this);
		mRlLoginOut.setOnClickListener(this);
		mRlMyCommunity.setOnClickListener(this);
		customer_service.setOnClickListener(this);
	}

	private void checkViewShow() {
		if (isLogin) {
			mTvLogin.setText("退出");
			mTvID.setVisibility(View.VISIBLE);
			mTvJifen.setVisibility(View.VISIBLE);
			mTvNickname.setVisibility(View.VISIBLE);
			mTvUnlogin.setVisibility(View.GONE);
		} else {
			mTvLogin.setText("登录");
			mTvID.setVisibility(View.GONE);
			mTvJifen.setVisibility(View.GONE);
			mTvNickname.setVisibility(View.GONE);
			mTvUnlogin.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		CrashHandler.d(TAG, TAG + " onDestroy");
		mCheckVersionListener.release();
		mUserInfoListener.release();
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		CrashHandler.d(TAG, TAG + " onDestroyView");
		((ViewGroup) mConvertView.getParent()).removeView(mConvertView);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		CrashHandler.d(TAG, TAG + " onPause");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		CrashHandler.d(TAG, TAG + " onResume");
	}

	private void init(LayoutInflater inflater) {
		mContext = getActivity().getApplicationContext();
		mTvJifen = (TextView) mConvertView.findViewById(R.id.tv_gold_num);
		mIvFace = (ImageView) mConvertView.findViewById(R.id.iv_header);
		mTvNickname = (TextView) mConvertView.findViewById(R.id.tv_nickname);
		mTvUnlogin = (TextView) mConvertView.findViewById(R.id.tv_unlogin);
		mTvID = (TextView) mConvertView.findViewById(R.id.tv_uniqueID);
		mTvLogin = (TextView) mConvertView.findViewById(R.id.tv_login);
		mTvVersion = (TextView) mConvertView.findViewById(R.id.tv_version);
		mIvVersionNew = (ImageView) mConvertView
				.findViewById(R.id.iv_version_new);
		tvpoint = (TextView)mConvertView.findViewById(R.id.tv_point);//积分
		shop_info = (LinearLayout)mConvertView.findViewById(R.id.shop_info);//加盟商
		mRlCollection = (RelativeLayout) mConvertView.findViewById(R.id.rl_discovery_collection);
		mRlOrderList = (RelativeLayout) mConvertView.findViewById(R.id.rl_discovery_orderlist);
		mRlCustiomservice = (RelativeLayout) mConvertView.findViewById(R.id.rl_discovery_customservice);
		mRlLoginOut = (RelativeLayout) mConvertView.findViewById(R.id.rl_login);
		mRlMyCommunity = (LinearLayout) mConvertView.findViewById(R.id.rl_discovery_my_community);
		mRlVersion = (RelativeLayout) mConvertView.findViewById(R.id.rl_discovery_version);
		mOfflineDialog = (OfflineDialog) inflater.inflate(R.layout.offline_dialog, null);
		customer_service = (LinearLayout)mConvertView.findViewById(R.id.customer_service);

		mConvertView.findViewById(R.id.rl_discovery_my_community).setOnClickListener(this);
		mRlVersion = (RelativeLayout) mConvertView.findViewById(R.id.rl_discovery_version);
		
		mConvertView.findViewById(R.id.layout_wait_for_pay).setOnClickListener(this);
		mConvertView.findViewById(R.id.layout_wait_for_receive).setOnClickListener(this);
		mConvertView.findViewById(R.id.layout_wait_for_evaluate).setOnClickListener(this);
		mConvertView.findViewById(R.id.layout_all_order).setOnClickListener(this);
		shop_info.setOnClickListener(this);
		erweima = (LinearLayout)mConvertView.findViewById(R.id.erweima);
		erweima.setOnClickListener(this);
		ly_agree = (LinearLayout) mConvertView.findViewById(R.id.ly_agree);
		ly_agree.setOnClickListener(this);
		ly_message = (LinearLayout) mConvertView.findViewById(R.id.ly_message);
		ly_message.setOnClickListener(this);
		checkViewShow();

		mTvVersion.setText("版本" + Tools.getAppVersionName(getActivity()));
		if (PreferenceModel.getBoolean(Define.SP_HAS_NEW_VERSION, false)) {
			mIvVersionNew.setVisibility(View.VISIBLE);
		} else {
			mIvVersionNew.setVisibility(View.GONE);
		}
		mFaceOptions = bulidOptions();

	}

	private DisplayImageOptions bulidOptions() {
		return new DisplayImageOptions.Builder()
				.showImageOnFail(R.drawable.ic_default_face)
				.showImageForEmptyUri(R.drawable.ic_default_face)
				.showImageOnLoading(R.drawable.ic_default_face)
				.cacheInMemory(true).cacheOnDisk(true)
				.displayer(new RoundedBitmapDisplayer(90)).build();
	}

	private static class MyUserInfoListener extends UserInfoListener {
		private FragmentPersonal mOuter;

		public MyUserInfoListener(FragmentPersonal outer) {
			mOuter = outer;
		}

		public void release() {
			new WeakReference<FragmentPersonal>(mOuter);
		}

		@Override
		public void onResponseSuccess(UserInfo userInfo) {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.mUserInfo = userInfo;
			mOuter.initView();
		}

		@Override
		public void onNoNetWork() {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
		}

		@Override
		public void onResponseFailed() {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
		}

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.rl_discovery_collection:
			if (!startLogin()) {
				getActivity().startActivity(new Intent(getActivity(),ShoppingSearchActivity.class));
			}
			break;
		case R.id.rl_discovery_orderlist:
			startActivity(new Intent(mContext, MyOrders.class));
			break;
		case R.id.rl_discovery_customservice:// 点击联系物业
			if (!startLogin()) {
				startActivity(new Intent(mContext, ContactTenement.class));
			}
			;
			break;
		case R.id.rl_discovery_version:
			System.checkVersion(getActivity(), "smh", mCheckVersionListener);
			break;
		case R.id.rl_discovery_my_community:
			if(!startLogin()){
				intent = new Intent(getActivity(), MyCommunityActivity.class);
				intent.putExtra("page", 4);
				startActivity(intent);
			}
			break;
		case R.id.rl_login:
			if (!startLogin()) {
				IAuth.getInstance().logout(buildListener());
			}
			break;

		case R.id.layout_wait_for_pay:
			if (!startLogin()) {
				intent = new Intent(mContext, MyOrders.class);
				intent.putExtra("name", "待支付订单");
				intent.putExtra("orderType", "0");
				startActivity(intent);
			}
			break;
			
		case R.id.layout_wait_for_evaluate:
			if (!startLogin()) {
				intent = new Intent(mContext, MyOrders.class);
				intent.putExtra("name", "待评价订单");
				intent.putExtra("orderType", "4");
				startActivity(intent);
			}
			break;
			
		case R.id.layout_wait_for_receive:
			if (!startLogin()) {
				intent = new Intent(mContext, MyOrders.class);
				intent.putExtra("name", "待收货订单");
				intent.putExtra("orderType", "1|2|8");
				startActivity(intent);
			}
			break;
			
		case R.id.layout_all_order:
			if (!startLogin()) {
				intent = new Intent(mContext, MyOrders.class);
				intent.putExtra("name", "全部订单");
				startActivity(intent);
			}
			break;
		case R.id.customer_service:
			String number = "03513077866";
			intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+ number));// 用intent启动拨打电话(只显示手机号码不直接拨打电话)
			startActivity(intent);
			break;
		case R.id.shop_info://点击加盟商，查看商家
			intent = new Intent(mContext,ShopIntroductActivity.class);
			startActivity(intent);
			break;
		case R.id.erweima://点击分享二维码
			intent = new Intent(mContext,ErweimaActivity.class);
			startActivity(intent);
			break;
		case R.id.ly_agree:
			intent = new Intent(mContext,UseragreementActivity.class);
			startActivity(intent);
			break;
		case R.id.ly_message:
			intent = new Intent(mContext,Browser.class);
			intent.putExtra("title", "消息中心");
			intent.putExtra("url", FragmentMall.msgurl+"uid="+mUserInfo.getUid());
			startActivity(intent);
			break;
		}
	}

	private LogoutListener buildListener() {
		return new LogoutListener() {

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(mContext, "退出失败, 请重试");
			}

			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(mContext, Define.MSG_NO_NETWORK);
			}

			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				IAuth.getInstance().clearUserInfo();
				if (LoginPlatform.QQ.getValue().equals(
						PreferenceModel.getString(
								Constants.PREFERENCE_KEY_LOGIN_PLATFORM, ""))
						&& Global.getInstance().getQQAuth().isSessionValid()) {
					Global.getInstance().getQQAuth().logout(mContext);
					CrashHandler.d(TAG, "退出QQ登录");
				}
				;
				getActivity().sendBroadcast(
						new Intent(Define.ACTION_EXIT_WHOLE_APP));
				startActivity(new Intent(getActivity(), Login.class));
			}
		};
	}

	public boolean startLogin() {
		if (IAuth.getInstance().loadCookieStore() == null) {
			startActivity(new Intent(getActivity(), Login.class));
			return true;
		}
		return false;
	}

	private static class MyCheckVersionListener extends CheckVersionListener {
		private FragmentPersonal mOuter;

		public MyCheckVersionListener(FragmentPersonal outer) {
			this.mOuter = outer;
		}

		public void release() {
			new WeakReference<FragmentPersonal>(mOuter);
		}

		@Override
		public void onResponseSuccess(CheckVersionInfo checkVersionInfo) {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.mLoadingDialog.dismiss();
			if (checkVersionInfo.isVersionLow()) {
				// private String versionName;
				// private String versionIntro;
				// private String downloadUrl;
				mOuter.showNoticeDialog(checkVersionInfo.getVersionIntro(),
						checkVersionInfo.getDownloadUrl());
			} else {
				Toast.makeText(mOuter.getActivity(), "当前已是最新版本",
						Toast.LENGTH_SHORT).show();
			}

		}

		@Override
		public void onNoMoreData() {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.mLoadingDialog.dismiss();
		}

		@Override
		public void onNoNetWork() {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.mLoadingDialog.dismiss();
			Toast.makeText(mOuter.getActivity(), Define.MSG_NO_NETWORK,
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onOffline() {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.mLoadingDialog.dismiss();
			mOuter.mOfflineDialog.show();
		}

		@Override
		public void onResponseFailed() {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.mLoadingDialog.dismiss();
			Toast.makeText(mOuter.getActivity(), "网络请求失败", Toast.LENGTH_SHORT)
					.show();
		}

	}

	public void showNoticeDialog(String updateMsg, final String apkUrl) {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle("发现新版本，是否要升级？");
		builder.setMessage(updateMsg);

		builder.setPositiveButton("升级", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				WriteCheckVersionTime();
				// showDownloadDialog();
				PreferenceModel.putBoolean(Define.KEY_HAS_NEW_VERSION, true);
				checkNewVersion();
				Uri uri = Uri.parse(apkUrl);
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				FragmentPersonal.this.getActivity().startActivity(intent);
			}

		});
		builder.setNegativeButton("以后再说",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						WriteCheckVersionTime();
						dialog.dismiss();
					}
				});
		Dialog noticeDialog = builder.create();
		noticeDialog.setCanceledOnTouchOutside(false);
		noticeDialog.setCancelable(false);
		noticeDialog.show();
	}

	protected void WriteCheckVersionTime() {

	}
			
		

	private void checkNewVersion() {
		boolean hasNewVersion = PreferenceModel.getBoolean(
				Define.KEY_HAS_NEW_VERSION, false);
		if (hasNewVersion) {
			mIvVersionNew.setVisibility(View.VISIBLE);
		} else {
			mIvVersionNew.setVisibility(View.GONE);
		}
	}

}
